package com.my.study.config.bean;


import com.my.study.config.ThreadPoolConfig;
import com.my.study.handler.MyRejectedExecutionHandler;
import com.tngtech.archunit.thirdparty.com.google.common.util.concurrent.ListeningExecutorService;
import com.tngtech.archunit.thirdparty.com.google.common.util.concurrent.MoreExecutors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableConfigurationProperties(ThreadPoolConfig.class)
public class ThreadConfig {

    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    @Bean
    public ThreadPoolTaskExecutor executor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(threadPoolConfig.getCorePoolSize());
        //配置最大线程数
        executor.setMaxPoolSize(threadPoolConfig.getMaxPoolSize());
        //配置队列大小
        executor.setQueueCapacity(threadPoolConfig.getQueueCapacity());
        //线程的名称前缀
        executor.setThreadNamePrefix(threadPoolConfig.getNamePrefix());
        //线程活跃时间（秒）
        executor.setKeepAliveSeconds(threadPoolConfig.getKeepAliveSeconds());
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置拒绝策略(可自定义)
        executor.setRejectedExecutionHandler(new MyRejectedExecutionHandler());
        //执行初始化
        executor.initialize();
        return executor;
    }

    @Bean
    public ListeningExecutorService getListeningExecutorService(ThreadPoolTaskExecutor threadPoolTaskExecutor){
        return MoreExecutors.listeningDecorator(threadPoolTaskExecutor.getThreadPoolExecutor());
    }
}
